package com.itlong.cloud.property.service.impl;

import com.itlong.cloud.POJO.DTO.property.PropertyInspectPlanTimeDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyInspectSettingDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.property.PropertyInspectSettingVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.PropertyInspectTypeEnum;
import com.itlong.cloud.property.dao.IPropertyInspectSettingDao;
import com.itlong.cloud.property.service.IPropertyInspectSettingService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      物业-巡检设置服务接口实现类
 * <desc/>
 *
 * @createDate 2019/12/24
 */
@Service
public class PropertyInspectSettingServiceImpl implements IPropertyInspectSettingService {

    @Autowired
    private IPropertyInspectSettingDao iPropertyInspectSettingDao;

    /**
     * <desc>
     *      添加巡检设置相关处理。
     * <desc/>
     *
     * @param  dto 巡检相关信息
     * @return
     * @author Juguang.S
     * @createDate 2019-12-24
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer saveInspectPoint(PropertyInspectSettingDTO dto) throws Exception {
        //巡检点对应一个巡检区域，巡检点对应路线是一对一，巡检路线对应巡检计划是多对多，巡检人员对应巡检路线是多对多
        SimpleDateFormat formatter = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
        Date date = new Date();
        String userId = dto.getLoginUserId();
        switch (PropertyInspectTypeEnum.getByEquipType(dto.getType())){
            case INSPECT_AREA:
                PropertyInspectAreaInfoPO areaInfoPO = new PropertyInspectAreaInfoPO();
                BeanUtils.copyProperties(dto,areaInfoPO);
                areaInfoPO.setCreateTime(date);
                areaInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                areaInfoPO.setInspectAreaId(LogicIdUtil.bussinessId());
                areaInfoPO.setCreateUserId(userId);
                return iPropertyInspectSettingDao.save(SqlUtil.durableData(areaInfoPO,PlatformConstants.TABLE_SAVE));
            case INSPECT_POINT:
                PropertyInspectPointInfoPO pointInfoPO = new PropertyInspectPointInfoPO();
                BeanUtils.copyProperties(dto,pointInfoPO);
                pointInfoPO.setCreateTime(date);
                pointInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                pointInfoPO.setInspectPointId(LogicIdUtil.bussinessId());
                pointInfoPO.setCreateUserId(userId);
                return iPropertyInspectSettingDao.save(SqlUtil.durableData(pointInfoPO, PlatformConstants.TABLE_SAVE));
            case INSPECT_LINE:
                PropertyInspectLineInfoPO lineInfoPO = new PropertyInspectLineInfoPO();
                BeanUtils.copyProperties(dto,lineInfoPO);
                //如果巡检路线Id不为空则为修改否则为新增
                if(StringUtils.isNotEmpty(lineInfoPO.getInspectLineId())){
                    lineInfoPO.setUpdateTime(date);
                    lineInfoPO.setOperateUserId(userId);
                    //如修改则需先把该路线所关联的巡检点删除 先查询出巡检路线先前关联的巡检点
                    iPropertyInspectSettingDao.updateInspectPoint(iPropertyInspectSettingDao.getInspectLineInfo(dto.getInspectLineId()).getInspectPointId().split(","),"");
                    iPropertyInspectSettingDao.update(SqlUtil.durableData(lineInfoPO, PlatformConstants.TABLE_UPDATE));
                }else{
                    lineInfoPO.setCreateTime(date);
                    lineInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                    lineInfoPO.setInspectLineId(LogicIdUtil.bussinessId());
                    lineInfoPO.setCreateUserId(userId);
                    iPropertyInspectSettingDao.save(SqlUtil.durableData(lineInfoPO,PlatformConstants.TABLE_SAVE));
                }
                //处理路线信息所关联的巡检点，将些路线ID更新至巡检点表中
                String[] pointArr = dto.getInspectPointId().split(",");
                return iPropertyInspectSettingDao.updateInspectPoint(pointArr,lineInfoPO.getInspectLineId());
            case INSPECT_PLAN:
                PropertyInspectPlanInfoPO planInfoPO = new PropertyInspectPlanInfoPO();
                List<Map<String, Object>> planProgramTimeInfoPOList = new ArrayList<>();
                BeanUtils.copyProperties(dto,planInfoPO);
                String planId = LogicIdUtil.bussinessId();
                //如果巡检计划Id不为空则为修改否则为新增
                if(StringUtils.isNotEmpty(dto.getInspectPlanId())){
                    //修改计划主表property_inspect_plan_info
                    planInfoPO.setUpdateTime(date);
                    planInfoPO.setOperateUserId(userId);
                    planInfoPO.setStartTime(formatter.parse(String.format("%s%s",dto.getPlanStartTime()," 00:00:00")));
                    planInfoPO.setEndTime(formatter.parse(String.format("%s%s",dto.getPlanEndTime()," 23:59:59")));
                    iPropertyInspectSettingDao.update(SqlUtil.durableData(planInfoPO, PlatformConstants.TABLE_UPDATE));
                    //删除计划附表
                    iPropertyInspectSettingDao.deletePlanProgramTimeInfo(dto.getInspectPlanId());
                }else{
                    planInfoPO.setInspectPlanId(planId);
                    planInfoPO.setCreateTime(date);
                    planInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                    planInfoPO.setInspectLineId(dto.getInspectLineId());
                    planInfoPO.setCreateUserId(userId);
                    planInfoPO.setStartTime(formatter.parse(String.format("%s%s",dto.getPlanStartTime()," 00:00:00")));
                    planInfoPO.setEndTime(formatter.parse(String.format("%s%s",dto.getPlanEndTime()," 23:59:59")));
                    iPropertyInspectSettingDao.save(SqlUtil.durableData(planInfoPO,PlatformConstants.TABLE_SAVE));
                }
                //处理日程类型所属的日期集合
                for(PropertyInspectPlanTimeDTO timeDTO : dto.getTimeArr()){
                    PropertyInspectPlanProgramTimeInfoPO planProgramTimeInfoPO = new PropertyInspectPlanProgramTimeInfoPO();
                    planProgramTimeInfoPO.setInspectPlanId(StringUtils.isNotEmpty(dto.getInspectPlanId())?dto.getInspectPlanId():planId);
                    planProgramTimeInfoPO.setProjectId(dto.getProjectId());
                    planProgramTimeInfoPO.setProgramTimeId(LogicIdUtil.bussinessId());
                    planProgramTimeInfoPO.setCreateTime(date);
                    planProgramTimeInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                    planProgramTimeInfoPO.setCreateUserId(userId);
                    planProgramTimeInfoPO.setStartTime(formatter.parse(String.format("%s%s",timeDTO.getStartTime(),":00")));
                    planProgramTimeInfoPO.setEndTime(formatter.parse(String.format("%s%s",timeDTO.getEndTime(),":00")));
                    planProgramTimeInfoPOList.add(SqlUtil.durableData(planProgramTimeInfoPO,PlatformConstants.TABLE_SAVE));
                }
                if(planProgramTimeInfoPOList!=null && planProgramTimeInfoPOList.size()>0){
                    return iPropertyInspectSettingDao.batchSave(planProgramTimeInfoPOList);
                }
                return null;
            default:
                return null;
        }

    }

    /**
     * <desc>
     *      获取巡检点编号 即蓝牙门禁deviceUnique。
     * <desc/>
     *
     * @param  dto 巡检点信息
     * @return
     * @author Juguang.S
     * @createDate 2019-12-24
     */
    @Override
    public List<String> getInspectPointNumber(PropertyInspectSettingDTO dto) {
        return iPropertyInspectSettingDao.getInspectPointNumber(dto.getProjectId());
    }

    /**
     * <desc>
     *      获取巡检设置相关分页列表。
     * <desc/>
     *
     * @param  dto 查询条件
     * @return 巡检分页集合
     * @author Juguang.S
     * @createDate 2019-12-24
     */
    @Override
    public Page<PropertyInspectSettingVO> getInspectInfoByPage(PropertyInspectSettingDTO dto) throws Exception {
        List<PropertyInspectSettingVO> list;
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(dto);
        Page<PropertyInspectSettingVO> page = new Page<>();
        page.getPage().setPageSize(dto.getPageSize());
        page.getPage().setCurrentPage(dto.getCurrentPage());
        params.put("projectId", dto.getProjectId());
        params.put("currentPage", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        switch (PropertyInspectTypeEnum.getByEquipType(dto.getType())){
            case INSPECT_AREA:
                page.setRows(iPropertyInspectSettingDao.getInspectAreaByPage(params),iPropertyInspectSettingDao.getInspectAreaByPageCount(params));
                return page;
            case INSPECT_POINT:
                page.setRows(iPropertyInspectSettingDao.getInspectPointByPage(params),iPropertyInspectSettingDao.getInspectPointByPageCount(params));
                return page;
            case INSPECT_LINE:
                page.setRows(iPropertyInspectSettingDao.getInspectLineByPage(params),iPropertyInspectSettingDao.getInspectLineByPageCount(params));
                return page;
            case INSPECT_PLAN:
                list = iPropertyInspectSettingDao.getInspectPlanByPage(params);
                for(PropertyInspectSettingVO settingVO : list){
                    settingVO.setInspectLineName(iPropertyInspectSettingDao.getInspectLineName(settingVO.getInspectLineId().split(",")));
                }
                page.setRows(list,iPropertyInspectSettingDao.getInspectPlanByPageCount(params));
                return page;
        }

        return page;
    }

    /**
     * <desc>
     *      修改巡检设置相关状态。
     * <desc/>
     *
     * @param  dto 修改状态相关参数 type 1巡检区域 2巡检点 3巡检路线 4巡检计划 inspectId配合type使用
     * @return
     * @author Juguang.S
     * @createDate 2019-12-24
     */
    @Override
    public Integer updateInspectSettingStatus(PropertyInspectSettingDTO dto) {
        //如果删除路线时，需将property_inspect_point_info表中点和路线的关联清除
        if(dto.getStatus()== DataStatusEnum.DELETE.getType() && dto.getType()==PropertyInspectTypeEnum.INSPECT_LINE.getType() ){
            iPropertyInspectSettingDao.updateInspecPointAndLineRelation(dto.getInspectId());
        }
        return iPropertyInspectSettingDao.updateInspectSettingStatus(dto);
    }

    /**
     * <desc>
     *      校验巡检区域、巡检点、巡检路线、巡检计划的名称是否存在。
     * <desc/>
     *
     * @param  dto 巡检相关信息
     * @return
     * @author Juguang.S
     * @createDate 2019-12-25
     */
    @Override
    public Integer isExistByInspectName(PropertyInspectSettingDTO dto) {
        switch (PropertyInspectTypeEnum.getByEquipType(dto.getType())) {
            case INSPECT_AREA:
                return iPropertyInspectSettingDao.isExistByInspectName(dto.getInspectAreaName(),dto.getType().toString(),dto.getProjectId());
            case INSPECT_POINT:
                return iPropertyInspectSettingDao.isExistByInspectName(dto.getInspectPointName(),dto.getType().toString(),dto.getProjectId());
            case INSPECT_LINE:
                return iPropertyInspectSettingDao.isExistByInspectName(dto.getInspectLineName(),dto.getType().toString(),dto.getProjectId());
            case INSPECT_PLAN:
                return iPropertyInspectSettingDao.isExistByInspectName(dto.getInspectPlanName(),dto.getType().toString(),dto.getProjectId());
        }
        return null;
    }

    /**
     * <desc>
     *      删除巡检相关需校验是否与上级有所关联，有关联不允许删除。
     * <desc/>
     *
     * @param  dto 巡检信息
     * @return 1巡检区域有关联 2巡检点有关联 3巡检路线有关联
     * @author Juguang.S
     * @createDate 2019-12-26
     */
    @Override
    public Integer isRelationByInspect(PropertyInspectSettingDTO dto) {
        switch (PropertyInspectTypeEnum.getByEquipType(dto.getType())) {
            case INSPECT_AREA:
                return iPropertyInspectSettingDao.isRelationByInspectArea(dto.getInspectId())>0?1:0;
            case INSPECT_POINT:
                return iPropertyInspectSettingDao.isRelationByInspectPoint(dto.getInspectId())>0?2:0;
            case INSPECT_LINE:
                return iPropertyInspectSettingDao.isRelationByInspectLine(dto.getInspectId())>0?3:0;
        }
        return 0;
    }

    /**
     * <desc>
     *      获取巡检路线或计划详情。
     * <desc/>
     *
     * @param  dto 巡检路线ID
     * @return 巡检路线详情
     * @author Juguang.S
     * @createDate 2019-12-26
     */
    @Override
    public PropertyInspectSettingVO getInspectLineInfo(PropertyInspectSettingDTO dto) {
        if(StringUtils.isNotEmpty(dto.getInspectLineId())){
            return iPropertyInspectSettingDao.getInspectLineInfo(dto.getInspectLineId());
        } else if(StringUtils.isNotEmpty(dto.getInspectPlanId())){
            PropertyInspectSettingVO settingVO = iPropertyInspectSettingDao.getInspectPlanInfo(dto.getInspectPlanId());
            settingVO.setInspectLineName(iPropertyInspectSettingDao.getInspectLineName(settingVO.getInspectLineId().split(",")));
            settingVO.setInspectUser(iPropertyInspectSettingDao.getInspectUserRealName(settingVO.getInspectUserId()));
            return settingVO;
        }else{
            return null;
        }
    }

    /**
     * <desc>
     *      获取巡检点列表。
     * <desc/>
     *
     * @param  dto 项目ID
     * @return 巡检点列表
     * @author Juguang.S
     * @createDate 2019-12-27
     */
    @Override
    public List<PropertyInspectSettingVO> getInspectPointList(PropertyInspectSettingDTO dto) {
        return iPropertyInspectSettingDao.getInspectPointList(dto.getProjectId());
    }

    /**
     * <desc>
     *      根据巡检相应ID获取名称。
     * <desc/>
     *
     * @param  dto 巡检相关信息
     * @return
     * @author Juguang.S
     * @createDate 2020-01-08
     */
    @Override
    public PropertyInspectSettingVO getInspectNameById(PropertyInspectSettingDTO dto) {
        PropertyInspectSettingVO settingVO;
        switch (PropertyInspectTypeEnum.getByEquipType(dto.getType())) {
            case INSPECT_AREA:
                settingVO = iPropertyInspectSettingDao.getInspectNameById(dto.getInspectAreaId(),dto.getType().toString());
                return settingVO==null?new PropertyInspectSettingVO():settingVO;
            case INSPECT_POINT:
                settingVO = iPropertyInspectSettingDao.getInspectNameById(dto.getInspectPointId(),dto.getType().toString());
                return settingVO==null?new PropertyInspectSettingVO():settingVO;
            case INSPECT_LINE:
                settingVO = iPropertyInspectSettingDao.getInspectNameById(dto.getInspectLineId(),dto.getType().toString());
                return settingVO==null?new PropertyInspectSettingVO():settingVO;
            case INSPECT_PLAN:
                settingVO = iPropertyInspectSettingDao.getInspectNameById(dto.getInspectPlanId(),dto.getType().toString());
                return settingVO==null?new PropertyInspectSettingVO():settingVO;
        }
        return null;
    }
}
